<template>
	<view class="indexs">
		<swiper class="swiper" v-if="homeInfo.images" :current="currIndex" indicator-dots circular :duration="1000">
			<swiper-item v-for="(item, index) in homeInfo.images" class="swiper-item" :key="index">
				<view class="">
					<image class="lb-image" :id="'wrap' + index" :src="item" mode="aspectFit" />
				</view>
			</swiper-item>
		</swiper>
		<!-- middle -->
		<view class="middle">
			<view class="djs">
				距离活动结束还有：
				<text class="num">{{ countdown.days }}</text>
				<text class="text">天</text>
				<text class="num">{{ countdown.hours }}</text>
				<text class="text">时</text>
				<text class="num">{{ countdown.minutes }}</text>
				<text class="text">分</text>
				<text class="num">{{ countdown.seconds }}</text>
				<text class="text">秒</text>
			</view>
			<view class="mid-mid">
				<view class="mid-mid-top">
					<view class="num-list">
						<view class="flex flex-direction align-center">
							<view class="num">{{ homeInfo.user_total}}</view>
							<view class="text">已报名</view>
						</view>
						<!-- <view class="line"></view> -->
						<view class="flex flex-direction align-center">
							<view class="num black">{{ homeInfo.number_of_votes }}</view>
							<view class="text">已投票</view>
						</view>
						<!-- <view class="line"></view> -->
						<view class="flex flex-direction align-center">
							<view class="num black">{{ (homeInfo.views) | numFilter }}</view>
							<view class="text">浏览量</view>
						</view>
					</view>
					<view class="bm-btn flex align-center justify-center" @click="go('baoming')">
						<view class="block"></view>
						<text class="text">{{ myStatus == -1 ? '我要报名' : '我的报名' }}</text>
						<view class="block"></view>
					</view>

					<!-- 			<view class="search">
						<view class="bg flex align-center">
							<input class="search-input" placeholder-style="color: rgba(255, 255, 255, 0.35);" placeholder="请输入选手名称或编号" type="text" v-model="keyword" />
							<view class="search-btn flex align-center justify-center" @click="getUserList">
								<text class="wlIcon-search"></text>
							</view>
						</view>
					</view> -->

					<view class="sq flex">
						<scroll-view scroll-x class="sq-scroll">
							<view class="sq-list">
								<view
									:class="['sq-item', item.province == province ? 'select' : '']"
									v-for="(item, index) in cityList"
									:key="index"
									@click="setProvince(item.province)"
								>
									{{ item.province }}
								</view>
							</view>
						</scroll-view>
						<view class="icon flex align-center justify-center" @click="tp">
							<text class="wlIcon-search"></text>
						</view>
					</view>
				</view>

				<view class="user-list">
					<view class="user-item" v-for="(item, index) in userList" :key="index" @click="go('xiangqing', item.id, item.activity_id)">
						<view class="bg flex">
							<view class="left flex-sub">
								<image v-if="index == 0" class="avat_flag" src="@/static/images/index/index_avat1.png" mode=""></image>
								<image v-if="index == 1" class="avat_flag" src="@/static/images/index/index_avat2.png" mode=""></image>
								<image v-if="index == 2" class="avat_flag" src="@/static/images/index/index_avat3.png" mode=""></image>
								<image class="user-img" :src="item.images_list[0]" mode=""></image>
							</view>
							<view class="mid flex-twice">
								<view class="flex">
									<text>{{ item.realname }}</text>
									<view class="num">{{ item.code }}号</view>
								</view>
								<view class="p flex-sub">
									<text>票数：</text>
									<text class="price">{{ +item.price }}票</text>
								</view>
							</view>
							<view class="right flex align-end">
								<view class="btn">投票</view>
							</view>
						</view>
					</view>
				</view>
				<uni-popup style="z-index: 999; height: auto" ref="popup" type="bottom" :is-mask-click="false">
					<view class="popup-content">
						<view class="flex justify-between align-center">
							<view class="title">筛选赛区</view>
							<view class="close" @click="close">取消</view>
						</view>
						<scroll-view scroll-y="true" class="city-box">
							<t-city @setProvince="setProvince" @searchCity="searchCity" />
						</scroll-view>
					</view>
				</uni-popup>
			</view>
		</view>
	</view>
</template>

<script>
import TCity from '@/components/t-city.vue';
let time;
let rsTime;
export default {
	components: { TCity },

	data() {
		return {
			myStatus: -1,
			countdown: {
				days: 0,
				hours: 0,
				minutes: 0,
				seconds: 0
			},
			keyword: '', //搜索值
			cityList: [],
			province: '', //赛区index
			userList: [], //参赛选手列表
			homeInfo: {},
			currIndex: 0, // 当前索引
			swiperHeight: 0, // 滑块的高度(单位px)
			pages: 1,
			loading: false,
			time: null
		};
	},
	async onReachBottom() {
		if (this.loading) {
			this.pages++;
			this.getUserList();
		}
	},
	onReady() {},
	async onLoad(query) {
		await this.getHome();
		await this.getCityList();
		this.getUserList();
		let [err, r] = await uni.request({
			url: `/wanlshop/activity/Index/getDetailStatus?activity_id=${this.homeInfo.id}`,
			method: 'GET'
		});
		this.myStatus = +r.data.status;
		// this.$nextTick(() => {
		// 	this.setSwiperHeight(); // 动态设置 swiper 的高度
		// });

		// 检测登录
		if(!(r.data.code == '401')) {
			this.getVoteData()
			this.time = setInterval(this.getVoteData, 5000);
		} else {
			// #ifdef H5
			if(this.$jssdk.isWechat()) {
				// 微信内置浏览器登录
				await this.toAuthorize()
			} else {
				let page = this.$mp.page;
				this.pageroute = encodeURIComponent(`/${page.route}?${this.$wanlshop.parseParams(page.options)}`);
			}
			// #endif
		}
	},
	onHide() {
		console.log('onUnload')
		clearInterval(this.time);
		clearInterval(this.rsTime);
	},
	filters: {
		// 转换浏览量w
		numFilter(v) {
			return v ? (v /10000).toFixed(1) + 'w' : '***'
		}
	},
	methods: {
		calculateCountdown() {
			const now = Math.floor(Date.now() / 1000); // 当前时间戳
			const diff = this.homeInfo.end_time - now;
			if (diff >= 0) {
				this.countdown.days = Math.floor(diff / (24 * 60 * 60));
				this.countdown.hours = Math.floor((diff % (24 * 60 * 60)) / (60 * 60));
				this.countdown.minutes = Math.floor((diff % (60 * 60)) / 60);
				this.countdown.seconds = diff % 60;
			} else {
				this.countdown.days = 0;
				this.countdown.hours = 0;
				this.countdown.minutes = 0;
				this.countdown.seconds = 0;
				clearInterval(time);
			}
		},
		async getHome() {
			let [err, res] = await uni.request({
				url: `/wanlshop/activity/Index/getActivity`,
				method: 'GET'
			});
			res.data.number_of_votes = '***'
			res.data.user_total = '***'
			res.data.views = null
			this.homeInfo = res.data;
			
			time = setInterval(this.calculateCountdown, 1000);
		},
		async getCityList() {
			let [err, res] = await uni.request({
				url: `/wanlshop/activity/Index/cityList`,
				method: 'GET'
			});
			this.province = res.data?.[0]?.['province'];
			this.cityList = res.data;
		},
		getUserList() {
			let keyword = this.keyword,
				province = this.province == '中国' ? '' : this.province;
			uni.request({
				url: `/wanlshop/activity/Index/getActivityUserList?keyword=${keyword}&province=${province}&page=${this.pages}&activity_id=${this.homeInfo.id}`,
				method: 'GET',
				success: (res) => {
					console.log(res.data.data);
					if (res.data.last_page > this.pages) {
						this.loading = true;
					} else {
						this.loading = false;
					}
					res.data.data = res.data.data.map(item => {
						const img0 = item.images_list[0] + '?x-oss-process=image/resize,m_mfit,w_200,h_200/crop,w_200,h_200'
						item.images_list[0] = img0
						return {
							...item
						}
					})
					this.userList = this.userList.concat(...res.data.data)
				}
			});
		},
		/**
		 *
		 * 切换赛区
		 */
		setProvince(value) {
			this.province = value;
			this.pages = 1;
			this.userList = [];
			this.getUserList();
			this.close();
		},
		searchCity(value) {
			this.keyword = value;
			this.pages = 1;
			this.userList = [];
			this.getUserList();
			this.close();
		},
		tp() {
			this.$refs.popup.open('bottom');
		},
		close() {
			this.$refs.popup.close();
		},
		async go(type, id, activity_id) {
			if (type == 'baoming') {
				let [err, r] = await uni.request({
					url: `/wanlshop/activity/Index/getDetailStatus?activity_id=${this.homeInfo.id}`,
					method: 'GET'
				});
				if (r.data.code == 401) {
					return this.$wanlshop.to('/pages/user/auth/auth');
				}
				this.myStatus = +r.data.status;
				switch (this.myStatus) {
					case 1:
						uni.navigateTo({
							url: `/pages/${type}/${type}?type=look`
						});
						break;
					case -1:
						uni.navigateTo({
							url: `/pages/${type}/${type}`
						});
						break;
					case 0:
						uni.navigateTo({
							url: `/pages/tj/tj?type=${0}`
						});
						break;
					case 2:
						uni.navigateTo({
							url: `/pages/tj/tj?type=${1}&name=${r.data.reject}`
						});
						break;
					case 3:
						uni.navigateTo({
							url: `/pages/tj/tj?type=${3}`
						});
						break;
				}
				return;
			}
			uni.navigateTo({
				url: `/pages/${type}/${type}?id=${id}&activity_id=${activity_id}`
			});
		},
		getVoteData() {
			uni.request({
				url: `/wanlshop/activity/Index/activityRealInfo?activity_id=${this.homeInfo.id}`,
				method: 'GET',
				success: (res) => {
					console.log(111, res);
					this.homeInfo.number_of_votes = res.data.number_of_votes;
					this.homeInfo.user_total = res.data.user_total;
					this.homeInfo.views = res.data.views
				}
			});
		},
		async toAuthorize() {
			let that = this
			let local = window.location.href; // 获取页面url
			let code = this.getUrlCode().code; // 截取code
			// 获取之前的code
			let oldCode = uni.getStorageSync('wanlshop:code');
			// 如果没有code，就去请求获取code
			if (code == null || code === '' || code == 'undefined' || code == oldCode) {
				uni.showModal({
					title: '提示',
					content: '是否去授权获取您的个人信息~',
					success: function (res) {
						if (res.confirm) {
							let uri = encodeURIComponent(local);
							let page = that.$mp.page;
							uni.setStorageSync('wanlshop:code', 0); // 设置旧的code为0，避免死循环
							window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${that.$wanlshop.config('appid')}&redirect_uri=${uri}&forcePopup=true&response_type=code&scope=snsapi_userinfo&state=${encodeURIComponent(`/${page.route}?${that.$wanlshop.parseParams(page.options)}`)}#wechat_redirect`
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			} else {
				console.log('code', code)
				console.log('getUrlCode', this.getUrlCode())
				let pageroute = this.getUrlCode().state; // 截取state
				uni.setStorageSync('wanlshop:code', code); // 保存最新code
				await uni.request({
					url: '/wanlshop/user/third',
					method: 'POST',
					data: {
						platform: 'h5_weixin',
						code: code,
						client_id: uni.getStorageSync("wanlshop:chat_client_id") ? uni.getStorageSync("wanlshop:chat_client_id") : null
					},
					success: res => {
						
						this.$store.dispatch('user/login', res.data);
						this.$store.dispatch('cart/login');
						this.$store.dispatch('chat/get');
						uni.reLaunch({url: '/pages/index'});
						// uni.reLaunch({url: decodeURIComponent(pageroute)});
					}
				});
			}
		},
		getUrlCode() {
			// 截取url中的code方法
			var url = location.search;
			// this.winUrl = url;
			var theRequest = new Object();
			if (url.indexOf('?') != -1) {
				var str = url.substr(1);
				var strs = str.split('&');
				for (var i = 0; i < strs.length; i++) {
					theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
				}
			}
			return theRequest;
		},
		// /* 切换 swiper 滑块 */
		// changeSwiper(e) {
		// 	this.currIndex = e.detail.current;
		// 	this.$nextTick(() => {
		// 		this.setSwiperHeight(); // 动态设置 swiper 的高度
		// 	});
		// },
		// /* 动态设置 swiper 的高度 */
		// setSwiperHeight() {
		// 	const element = '#wrap' + this.currIndex;
		// 	const query = uni.createSelectorQuery().in(this);
		// 	query.select(element).boundingClientRect();
		// 	query.exec((res) => {
		// 		console.log(res);
		// 		if (res && res[0]) this.swiperHeight = res[0].height;
		// 	});
		// }
	}
};
</script>

<style lang="scss" scoped>
.indexs {
	background: url('@/static/images/index/index_bg.png') no-repeat top center;
	background-size: cover;
	min-height: 100vh;
	// background-color: $bg1;
	.swiper {
		width: 750rpx;
		height: 500rpx;
		.swiper-item {
			overflow: hidden;
			width: 750rpx;
			height: 100%;
		}

		.lb-image {
			height: 500rpx;
			// width: 750rpx;
		}
	}
	.middle {
		background: url('@/static/images/index/index_bg.png') no-repeat top center;
		background-size: cover;
		// background: linear-gradient(90deg, rgba(227,249,254, 1) 0%, #fff 50%, #F9E5F3 100%);

		border-radius: 40rpx;
		position: relative;
		top: -16px;

		.mid-mid {
			width: 96%;
			margin: 0 auto;
			.mid-mid-top {
				border-radius: 40rpx 40rpx 0 0;
				background: linear-gradient(90deg, rgba(227, 249, 254, 1) 0%, #fff 50%, #f9e5f3 100%);
			}
		}
	}
	.num-list {
		display: flex;
		justify-content: space-around;
		height: 160rpx;
		align-items: baseline;
		background: url('@/static/images/index/index_bg2.png') no-repeat top center;
		background-size: cover;
		margin-bottom: 28rpx;
		border-radius: 40rpx;
		.line {
			height: 100rpx;
			border: 2rpx solid rgba(255, 255, 255, 0.05);
		}

		.num {
			font-size: 34rpx;
			font-weight: 900;
			letter-spacing: 1.7rpx;
			line-height: 47.6rpx;
			color: rgba(223, 39, 233, 1);
			margin: 40rpx 0 10rpx 0;
		}

		.black {
			color: #261332;
		}

		.text {
			font-size: 28rpx;
			font-weight: 500;
			letter-spacing: 1.2rpx;
			line-height: 33.6rpx;
			color: #a296b3;
		}
	}

	.djs {
		text-align: center;
		font-size: 28rpx;
		font-weight: 500;
		letter-spacing: 1.4rpx;
		color: #1c1b1b;
		padding: 40rpx 0;

		.num {
			font-family: PingFang SC;
			padding: 8rpx 10rpx;
			font-size: 28rpx;
			color: #ffffff;
			background: #ff9fec;
			border-radius: 5px 5px 5px 5px;
		}
		.text {
			margin: 0 6rpx;
		}
	}

	.bm-btn {
		margin: 0 auto;
		width: 640rpx;
		height: 100rpx;
		opacity: 1;
		border-radius: 10rpx;
		font-size: 32rpx;
		font-weight: 900;
		letter-spacing: 1.6rpx;
		color: rgba(255, 255, 255, 1);
		background: linear-gradient(270deg, #ff74e1 0%, #e994ff 100%);
		box-shadow: inset 0px 10px 10px 0px rgba(255, 236, 242, 0.67);
		border-radius: 100px 100px 100px 100px;
		font-size: 32rpx;
		color: #ffffff;
		text-shadow: 0px 4px 10px rgba(255, 59, 120, 0.7216);
		margin-bottom: 32rpx;
		.text {
			margin: 0 50rpx;
		}
		.block {
			width: 10rpx;
			height: 10rpx;
			background-color: #fff;
			border-radius: 50%;
		}
	}
	.search {
		margin: 50rpx auto;
		width: 700rpx;
		height: 88rpx;
		border-radius: 10rpx;
		padding: 4rpx;
		background: linear-gradient(90deg, rgba(170, 40, 248, 1) 0%, rgba(96, 69, 251, 1) 100%);
		.bg {
			position: relative;
			border-radius: 10rpx;
			background-color: $bg1;
			width: 100%;
			height: 100%;
		}
		.search-input {
			background-color: #F3F3F3;
			flex: 1;
			height: 100%;
			padding: 20rpx;
			padding-right: 88rpx;
			font-size: 28rpx;
			font-weight: 500;
			letter-spacing: 1.4rpx;
			line-height: 39.2rpx;
			color: #fff;
		}
		.search-btn {
			position: absolute;
			right: -4rpx;
			color: #fff;
			font-size: 40rpx;
			border-radius: 0 10rpx 10rpx 0;
			width: 74rpx;
			height: 88rpx;
			background: linear-gradient(270deg, rgba(170, 40, 248, 1) 0%, rgba(96, 69, 251, 1) 100%);
		}
	}
	.sq {
		// margin-left: 24rpx;
		width: 96%;
		margin-left: 28rpx;
		background: #fcf1ff;
		border-radius: 200rpx 0 0 200rpx;
		.icon {
			color: #fff;
			width: 100%;
			background: linear-gradient(90deg, rgba(97, 68, 251, 0.5) 0%, rgba(170, 40, 248, 0.5) 100%);
			border-radius: 10rpx 0rpx 0rpx 10rpx;
			font-size: 40rpx;
		}

		.sq-scroll {
			width: 92%;
		}
		.sq-list {
			width: 999rpx;
			display: flex;
		}
		.sq-item {
			display: inline-block;
			margin-right: 20rpx;
			font-size: 28rpx;
			font-weight: 500;
			letter-spacing: 1.4rpx;
			color: #261332;
			overflow: hidden;
			padding: 14rpx 0;
			flex: 0 0 auto;
			width: 144rpx;
			text-align: center;
			&.select {
				background: linear-gradient(105deg, #ff6dc4 0%, #e994ff 100%);
				border-radius: 200rpx;
				color: #ffffff;
			}
		}
	}
	.user-list {
		padding: 30rpx 20rpx;
		background: #ffffff;
		background: linear-gradient(130deg, rgba(227, 249, 254, 1) 0%, #fff 20%);
		.user-item {
			box-shadow: 1px 1px 6px 2px rgba(254, 117, 150, 0.12);
			border-radius: 20rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
			.user-img {
				width: 118rpx;
				height: 118rpx;
				border-radius: 50%;
			}
			.left {
				position: relative;
				.avat_flag {
					position: absolute;
					width: 132rpx;
					height: 142rpx;
					top: -22rpx;
					left: -4rpx;
				}
			}
			.mid {
				margin-top: 18rpx;
				.num {
					padding: 4rpx 16rpx;
					background: #fff1fc;
					border-radius: 200rpx;
					font-size: 24rpx;
					color: #a271a9;
					margin-left: 20rpx;
				}

				.p {
					margin-top: 20rpx;
					.price {
						font-size: 28rpx;
						color: #ec5bff;
					}
				}
			}

			.right {
				.btn {
					background: linear-gradient(270deg, #fd77e4 0%, #ea92fd 100%);
					box-shadow: inset 0px 5px 3px 0px rgba(255, 254, 254, 0.3);
					border-radius: 200rpx;
					padding: 16rpx 54rpx;
					font-size: 30rpx;
					color: #ffffff;
					text-shadow: 0px 1px 5px #ec5bff;
				}
			}
		}
	}
	.popup-content {
		background-color: #fff;
		padding: 26rpx;
		.title {
			font-size: 30rpx;
			color: #000000;
		}
		.close {
			text-align: right;
			padding: 10rpx;
			font-size: 28rpx;
			color: #3d3d3d;
		}
		.city-box {
			height: 60vh;
		}
	}
}
</style>